package com.vhall.component.service.data.utils;

import java.io.*;
import java.util.List;
import java.util.stream.Collectors;

/**
 * csv utils
 *
 * @author guoxin.wang
 * @date 2021-05-17 15:23
 */
public class CsvUtil {

    /**
     * CSV文件生成方法
     *
     * @param head       标题列
     * @param dataList   数据列
     * @param outPutPath 输出目录
     * @param filename   文件名字
     * @return file
     */
    public static File createCsvFile(List<String> head, List<List<String>> dataList, String outPutPath, String filename) {
        File csvFile = null;
        try {
            csvFile = new File(outPutPath + File.separator + filename);
            File parent = csvFile.getParentFile();
            if (parent != null && !parent.exists()) {
                parent.mkdirs();
            }
            csvFile.createNewFile();

            // GB2312使正确读取分隔符","
            try (BufferedWriter csvWtriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(csvFile), "UTF-8"), 1024)) {
                // 写入文件头部
                writeRow(head, csvWtriter);
                // 写入文件内容
                for (List<String> row : dataList) {
                    writeRow(row, csvWtriter);
                }
                csvWtriter.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return csvFile;
    }

    /**
     * 写一行数据方法
     *
     * @param row       单行数据
     * @param csvWriter 操作的流
     * @throws IOException io exception
     */
    public static void writeRow(List<String> row, BufferedWriter csvWriter) throws IOException {
        String str = row.stream().collect(Collectors.joining(","));
        csvWriter.write(new String(new byte[]{(byte) 0xEF, (byte) 0xBB, (byte) 0xBF}));
        csvWriter.write(str);
        csvWriter.newLine();
    }
}
